/**
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 *         
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. Unless required by applicable law or
 * agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */
package org.rhok.ncn.background;

import java.util.concurrent.TimeUnit;

import org.rhok.ncn.common.CommonData;
import org.rhok.ncn.common.Utils;

import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

/**
 * Runs in the background, periodically checking the wifi signal strength and updating the
 * application context to include any new changes for use in recording data.
 * @author pfritzsche
 *
 */
public class WifiSignalTracker extends DaemonThread {
	
	private final WifiManager manager;

	/**
	 * Public constructor
	 * @param common Shared application context, to be used for data sharing between classes
	 * @param manager the Android wifi manager, to be used to get the wifi signal strength
	 */
	public WifiSignalTracker(WifiManager manager) {
	    super(TimeUnit.MINUTES.toMillis(1));
		this.manager = manager;
	}
	
	/**
	 * Gathers the current wifi strength every 1 minute, if there is a signal strength to gather.
	 * Updates the wifi signal text view to contain the new information and updates the context to
	 * reflect any changes.
	 */
	@Override
	protected void runOnce() {
	    if (manager.getWifiState() != WifiManager.WIFI_STATE_DISABLED) {
	        WifiInfo connInfo = manager.getConnectionInfo();
	        if (connInfo != null) {
	            int norm = WifiManager.calculateSignalLevel(connInfo.getRssi(), 5);
	            CommonData.wifiStrength = norm;
	            Utils.updateLocation(null);
	        }
	    }
	}
}
